import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_hsh/utils/k_log.dart';
import 'package:flutter_hsh/utils/toast_utils.dart';
import 'package:get/get.dart';
import '../../fluttergromore/plugin/health_score.dart';

class HealthScoreLogic extends GetxController {
  // 响应式状态
  final Rx<HealthScoreResult?> healthScore = Rx<HealthScoreResult?>(null);
  final RxBool isLoading = false.obs;
  final RxString errorMessage = ''.obs;
  
  // 功能优化相关状态
  final RxBool isBoosting = false.obs; // 手机加速状态
  final RxString securityStatus = '未检测'.obs; // 安全检测状态
  final RxDouble currentTemperature = 45.0.obs; // 当前温度
  final RxDouble memoryProgress = 0.75.obs; // 内存使用进度

  // 首页功能红点可控（根据用户操作隐藏，仅安全检测在有风险时显示）
  // 默认：四项功能显示红点，安全检测红点默认不显示，扫描出风险时才显示
  final RxBool showJunkDot = true.obs;       // 垃圾清理红点
  final RxBool showBoostDot = true.obs;      // 手机加速红点
  final RxBool showCooldownDot = true.obs;   // 手机降温红点
  final RxBool showMemoryDot = true.obs;     // 释放内存红点（文件碎片）
  final RxBool showSecurityDot = false.obs;  // 安全检测红点（仅有风险时显示）

  @override
  void onInit() {
    super.onInit();
    KLog.d("HealthScoreLogic onInit");
    _getHealthScore();
  }

  @override
  void onReady() {
    super.onReady();
    KLog.d("HealthScoreLogic onReady");
  }

  /// 获取健康评分
  Future<void> _getHealthScore() async {
    try {
      isLoading.value = true;
      errorMessage.value = '';
      
      final score = await HealthScore.getHealthScore();
      healthScore.value = score;
      
      KLog.d("健康评分获取成功: ${score.overallScore}");
    } catch (e) {
      errorMessage.value = e.toString();
      KLog.d("获取健康评分失败: $e");
    } finally {
      isLoading.value = false;
    }
  }

  /// 刷新健康评分
  Future<void> refreshHealthScore() async {
    await _getHealthScore();
  }

  /// 获取评分颜色
  Color getScoreColor([double? score]) {
    final s = score ?? healthScore.value?.overallScore ?? 0;
    if (s >= 80) return Colors.green;
    if (s >= 60) return Colors.orange;
    return Colors.red;
  }

  /// 获取评分描述
  String getScoreDescription(double score) {
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '一般';
    if (score >= 60) return '注意';
    return '需改善';
  }

  /// 获取温度状态文本
  String getTemperatureStatusText(String status) {
    switch (status) {
      case 'normal': return '正常';
      case 'high': return '偏高';
      case 'overheat': return '过高';
      default: return '未知';
    }
  }

  /// 获取安全风险文本
  String getSecurityRiskText(String riskLevel) {
    switch (riskLevel) {
      case 'none': return '无风险';
      case 'low': return '低风险';
      case 'high': return '高风险';
      default: return '未知';
    }
  }

  /// 获取温度颜色
  Color getTemperatureColor(double temperature) {
    if (temperature < 40) return Colors.green;
    if (temperature < 50) return Colors.orange;
    return Colors.red;
  }

  /// 垃圾清理
  Future<void> cleanupJunk() async {
    try {
      MyToast.show('开始清理垃圾文件...');
      // 模拟清理过程
      await Future.delayed(const Duration(seconds: 2));
      MyToast.show('垃圾清理完成，释放了 1.2GB 空间');
    } catch (e) {
      MyToast.show('清理失败：${e.toString()}');
    }
  }

  /// 手机加速
  Future<void> boostPhone() async {
    if (isBoosting.value) return;
    
    try {
      isBoosting.value = true;
      MyToast.show('正在加速手机...');
      // 模拟加速过程
      await Future.delayed(const Duration(seconds: 3));
      MyToast.show('手机加速完成，运行速度提升 35%');
    } catch (e) {
      MyToast.show('加速失败：${e.toString()}');
    } finally {
      isBoosting.value = false;
    }
  }

  /// 安全检测
  Future<void> scanSecurity() async {
    try {
      securityStatus.value = '检测中...';
      MyToast.show('开始安全检测...');
      // 模拟检测过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 模拟检测结果
      final hasRisk = DateTime.now().millisecond % 2 == 0;
      securityStatus.value = hasRisk ? '发现风险' : '安全';
      // 根据检测结果控制首页“安全检测”红点：有风险才显示
      showSecurityDot.value = hasRisk;
      MyToast.show(hasRisk ? '检测到安全风险，建议立即处理' : '设备安全，未发现风险');
    } catch (e) {
      securityStatus.value = '检测失败';
      MyToast.show('检测失败：${e.toString()}');
    }
  }

  /// 手机降温
  Future<void> coolDownPhone() async {
    try {
      MyToast.show('开始手机降温...');
      // 模拟降温过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 降低温度（默认降低 5℃），并同步到健康分的温度项
      currentTemperature.value = math.max(35.0, currentTemperature.value - 5.0);
      _applyTemperatureToScore(currentTemperature.value);
      MyToast.show('手机降温完成，当前温度：${currentTemperature.value.toStringAsFixed(1)}°C');
    } catch (e) {
      MyToast.show('降温失败：${e.toString()}');
    }
  }

  /// 释放内存
  Future<void> releaseMemory() async {
    try {
      MyToast.show('正在释放内存...');
      // 模拟内存释放过程
      await Future.delayed(const Duration(seconds: 2));
      
      // 减少内存使用，并同步到健康分的内存项
      final double drop = 0.2; // 释放20%的使用进度
      memoryProgress.value = math.max(0.0, memoryProgress.value - drop);
      _applyMemoryProgressToScore(memoryProgress.value);
      MyToast.show('内存释放完成，释放了 ${(drop * 100).toStringAsFixed(0)}% 的内存');
    } catch (e) {
      MyToast.show('释放失败：${e.toString()}');
    }
  }

  // ================= 评分联动更新（本地调整） =================

  /// 对外暴露：按指定降温值（℃）应用到当前温度并更新评分
  void applyTemperatureDrop(double dropDegrees) {
    // 更新当前温度（最低保留到 35℃，避免不合理显示）
    currentTemperature.value = math.max(35.0, currentTemperature.value - dropDegrees);
    _applyTemperatureToScore(currentTemperature.value);
    // 用户已完成“手机降温”，隐藏该功能红点
    showCooldownDot.value = false;
  }

  /// 对外暴露：按指定释放比例（0~1）降低内存使用并更新评分
  void applyMemoryRelease(double dropFraction) {
    final df = dropFraction.clamp(0.0, 1.0);
    memoryProgress.value = math.max(0.0, memoryProgress.value - df);
    _applyMemoryProgressToScore(memoryProgress.value);
    // 用户已完成“释放内存”，隐藏该功能红点
    showMemoryDot.value = false;
  }

  /// 将当前温度写入健康分中的温度项，并重算综合分
  void _applyTemperatureToScore(double temperature) {
    // 关键说明：本方法不调用原生接口，直接在当前模型上进行本地调整，确保用户操作后的结果能即时体现在 UI 上
    final current = healthScore.value;
    if (current == null) return; // 提前返回避免空引用

    // 根据温度计算状态
    String status;
    if (temperature <= 40) {
      status = 'normal';
    } else if (temperature <= 50) {
      status = 'high';
    } else {
      status = 'overheat';
    }

    // 根据温度映射分数（简单分段映射，便于理解与维护）
    // 35℃及以下：100分；40℃及以下：90分；45℃及以下：80分；50℃及以下：70分；其他：50分
    double tScore;
    if (temperature <= 35) {
      tScore = 100;
    } else if (temperature <= 40) {
      tScore = 90;
    } else if (temperature <= 45) {
      tScore = 80;
    } else if (temperature <= 50) {
      tScore = 70;
    } else {
      tScore = 50;
    }

    final newTemperature = TemperatureScore(
      score: tScore,
      temperature: temperature,
      status: status,
    );

    _updateHealthScoreWith(
      temperature: newTemperature,
    );
  }

  /// 将当前内存进度（0~1）写入健康分中的内存项，并重算综合分
  void _applyMemoryProgressToScore(double progress) {
    final current = healthScore.value;
    if (current == null) return;

    // 将0~1的进度映射为百分比
    final usagePercent = (progress.clamp(0.0, 1.0)) * 100.0;
    // 分数采用“使用率越低分数越高”的简单公式：100 - 使用率
    final mScore = (100.0 - usagePercent).clamp(0.0, 100.0);

    final newMemory = MemoryScore(
      score: mScore,
      totalMemory: current.memory.totalMemory,
      availableMemory: current.memory.availableMemory, // 此处不改字节统计，仅改展示与评分
      usagePercentage: usagePercent,
    );

    _updateHealthScoreWith(
      memory: newMemory,
    );
  }

  /// 垃圾清理释放存储空间后，按释放字节数更新存储评分并重算综合分
  void applyStorageFreed(int freedBytes) {
    final current = healthScore.value;
    if (current == null) return;

    final total = current.storage.totalStorage;
    final available = current.storage.availableStorage;
    // 增加可用空间，确保不超过总空间
    // 注意：dart:math 的 min/max 返回 num，这里用纯整型逻辑避免类型不匹配
    final int safeFreed = freedBytes < 0 ? 0 : freedBytes; // 负值防御
    final int newAvailableTemp = available + safeFreed;
    final int newAvailable = newAvailableTemp > total ? total : newAvailableTemp; // 限制不超过总空间
    final int used = total - newAvailable; // used 保证为整型并且非负
    final usagePercent = total > 0 ? (used / total) * 100.0 : current.storage.usagePercentage;
    final sScore = (100.0 - usagePercent).clamp(0.0, 100.0);

    final newStorage = StorageScore(
      score: sScore,
      totalStorage: total,
      availableStorage: newAvailable,
      usagePercentage: usagePercent,
    );

    _updateHealthScoreWith(
      storage: newStorage,
    );

    // 用户已完成“垃圾清理”，隐藏该功能红点
    showJunkDot.value = false;
  }

  /// 用新的子项（可选）更新健康分，并重算 overallScore
  void _updateHealthScoreWith({
    MemoryScore? memory,
    StorageScore? storage,
    TemperatureScore? temperature,
  }) {
    final current = healthScore.value;
    if (current == null) return;

    final newMemory = memory ?? current.memory;
    final newStorage = storage ?? current.storage;
    final newTemperature = temperature ?? current.temperature;
    final newSecurity = current.security; // 暂不在本次联动中修改安全项

    final overall = _computeOverall(
      newMemory.score,
      newStorage.score,
      newTemperature.score,
      newSecurity.score,
    );

    healthScore.value = HealthScoreResult(
      overallScore: overall,
      memory: newMemory,
      storage: newStorage,
      temperature: newTemperature,
      security: newSecurity,
    );
  }

  /// 简单综合分计算：四项平均分（便于理解与维护）
  double _computeOverall(
    double m,
    double s,
    double t,
    double sec,
  ) {
    return ((m + s + t + sec) / 4.0).clamp(0.0, 100.0);
  }

  /// 对外：标记“手机加速”已完成（隐藏红点）
  void markBoostCompleted() {
    showBoostDot.value = false;
  }
}